package com.ouran.common;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import com.google.common.hash.Hashing;
import com.ouran.model.page.Pager;

/**
 * 1、Spring默认的SimpleKeyGenerator是不会将函数名组合进key中的
 * 2、此外，原子类型的数组，直接作为key使用也是不会生效的:
 * (ClassCastException: java.lang.Long cannot be cast to java.lang.String)
 * 采用此方式后可以解决：多参数、原子类型数组、方法名识别 等问题
 * 为了解决上述2个问题，自定义了一个KeyGenerator
 * @author lijiajun
 *
 */
@Component("CacheKeyGenerator")
public class CacheKeyGenerator implements KeyGenerator {
	
	Logger logger = Logger.getLogger(CacheKeyGenerator.class);
    // custom cache key
    public static final int NO_PARAM_KEY = 0;
    public static final int NULL_PARAM_KEY = 53;
    
    @Override
    public Object generate(Object target, Method method, Object... params) {
 
        StringBuilder key = new StringBuilder();
        key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
        if (params.length == 0) {
            return key.append(NO_PARAM_KEY).toString();
        }
        for (Object param : params) {
            if (param == null) {
            	logger.warn("input null param for Spring cache, use default key="+NULL_PARAM_KEY);
                key.append(NULL_PARAM_KEY);
            } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
                int length = Array.getLength(param);
                for (int i = 0; i < length; i++) {
                    key.append(Array.get(param, i));
                    key.append(',');
                }
            } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
                key.append(param);
            } else if (param instanceof Pager) {//page分页方法取出 Offset作为缓存key的一部分，避免重复
                key.append(((Pager) param).getOffset());
            }
            else {
            	logger.warn("Using an object as a cache key may lead to unexpected results. " +
                        "Either use @Cacheable(key=..) or implement CacheKey. Method is " + target.getClass() + "#" + method.getName());
                key.append(param.hashCode());
            }
            key.append('-');
        }
 
        String finalKey = key.toString();
        long cacheKeyHash = Hashing.murmur3_128().hashString(finalKey, Charset.defaultCharset()).asLong();
        logger.info("using cache key="+finalKey +" hashCode="+cacheKeyHash);
        return key.toString();
    }
}
